package com.sport.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.*;

public class JsonUtil {
    /**
     * Json字符串转化为对象
     * @param json
     * @param clazz
     * @return
     */
    public static<T> T jsonToObj(String json,Class<T> clazz){
        System.out.println("进来了");
        return JSONObject.parseObject(json,clazz);
    }

    /**
     * 对象转化为Json字符串
     * @param object
     * @return
     */
    public static String objToJson(Object object) {
        return JSON.toJSONString(object);
    }

    /**
     * 根据序列化配置，将对象转化为Json字符串
     * @param object
     * @return
     */
    public static String objToJson(Object object, SerializerFeature feature) {
        return JSON.toJSONString(object,feature);
    }

    public static Map<String, Object> parseJSON2Map(String jsonStr){
        Map<String, Object> map = new HashMap<String, Object>();
        //最外层解析
        JSONObject json = JSONObject.parseObject(jsonStr);
        for(Object k : json.keySet()){
            Object v = json.get(k);
            //如果内层还是数组的话，继续解析
            if(v instanceof JSONArray){
                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
                Iterator<Object> it = ((JSONArray)v).iterator();
                while(it.hasNext()){
                    Object json2 = it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

}
